package com.jy.event.timer;

import com.jy.event.dao.CouponInstanceDao;
import com.jy.event.domain.CouponInstance;
import com.jy.event.domain.CouponInstanceStatus;
import com.jy.event.util.GateweyUtils;
import com.jy.event.util.LocalDateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * Created by lihu on 2018/3/24.
 */
@Slf4j
@Component
public class CouponInstanceTimer {


    @Autowired
    CouponInstanceDao couponInstanceDao;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    GateweyUtils gateweyUtils;


    /**
     * 轮询过期优惠卷（每3小时执行一次）
     * 查询规则 查询后一天到后两天 时间段到过期优惠卷
     * <p>
     * 每3小时执行一次
     */
    @Scheduled(cron = "0 0 */3 * * ?")  //每3小时执行一次
    public void overdue() {
        log.info(" overdue run ");
        try {
            LocalDateTime localDateTime = LocalDateTime.now().plusDays(1);
            //获取档期小时数
            int i = localDateTime.getHour();
            Date start = LocalDateTimeUtils.convertLDTToDate(localDateTime);
            //推送时间在8点到20 点
            if (i >= 0 && i < 18) {
                if (i <= 3) {
                    start = LocalDateTimeUtils.convertLDTToDate(localDateTime.minusHours(6));
                }

                Date end = LocalDateTimeUtils.convertLDTToDate(localDateTime.plusHours(3));
                List<CouponInstance> instances = couponInstanceDao.findByStautsAndEndTimeBetween(
                        CouponInstanceStatus.NORMAL, start, end);
                for (CouponInstance couponInstance : instances) {
                    try {
                        restTemplate.postForEntity(gateweyUtils.wechatRemind(), couponInstance, Object.class);
                    } catch (Exception ex) {
                        log.error("couponInstance is error:{}", couponInstance);
                    }

                }
            }
        } catch (Exception ex) {
            log.error("couponInstance is error:{}", ex);
        }


    }
}
